package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.provider.config.RedisInitRunner;
import com.csun.cmny.provider.constant.Constant;
import com.csun.cmny.provider.dao.OldmanLeaveMapper;
import com.csun.cmny.provider.dto.ShowAllLeaveDto;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.constant.OldInConstant;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.vo.old_out.AccountFundsOfLeyiVo;
import com.csun.cmny.provider.pojo.Bed;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.pojo.OldmanLeave;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.DateUtil;
import com.csun.cmny.provider.vo.OldmanLeaveVo;
import com.csun.cmny.provider.vo.SettleDetailVo;
import com.csun.cmny.util.PublicUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class OldmanLeaveServiceImpl implements OldmanLeaveService {

    @Resource
    private OmcOldManAccountFundsService omcOldManAccountFundsService;
    @Resource
    private OmcBillItemService omcBillItemService;
    @Resource
    private OldmanLeaveMapper oldmanLeaveMapper;
    @Resource
    private OldmanService oldmanService;
    @Resource
    private BedService bedService;
    @Resource
    private RedisInitRunner redisInitRunner;
    @Resource
    private CacRpcService cacRpcService;
    @Resource
    private OmcOldManBillService omcOldmanBillService;
    @Resource
    private OldmanRechargeService oldmanRechargeService;
    @Resource
    private OldmanNurseHiService oldmanNurseHiService;
    @Resource
    private OmcOldManSupplementService omcOldManSupplementService;
    @Resource
    private OmcOldmanExpenseItemService omcOldmanExpenseItemService;


    @Override
    public int deleteByPrimaryKey(Integer leaveId) {
        return oldmanLeaveMapper.deleteByPrimaryKey(leaveId);
    }

    @Override
    public int insert(OldmanLeave record) {
        return oldmanLeaveMapper.insert(record);
    }

    @Override
    public int insertSelective(OldmanLeave record) {
        return oldmanLeaveMapper.insertSelective(record);
    }

    @Override
    public OldmanLeave selectByPrimaryKey(OldmanLeave key) {
        return oldmanLeaveMapper.selectByPrimaryKey(key);
    }

    @Override
    public int updateByPrimaryKeySelective(OldmanLeave record) {
        return 0;
    }

    @Override
    public int updateByPrimaryKey(OldmanLeave record) {
        return 0;
    }

    @Override
    public List<OldmanLeaveVo> showAll(ShowAllLeaveDto dto) {
        return oldmanLeaveMapper.showAll(dto);
    }

    @Override
    public SettleDetailVo getLeaveByOid(Integer oldmanId) {
        return oldmanLeaveMapper.getLeaveByOid(oldmanId);
    }

    @Override
    public int updateByOid(OldmanLeave oldmanLeave) {
        return oldmanLeaveMapper.updateByOid(oldmanLeave);
    }

    @Override
    public int deleteByOid(Integer oldmanId) {
        return oldmanLeaveMapper.deleteByOid(oldmanId);
    }

    @Override
    public AccountFundsOfLeyiVo getSettleDetailByOldmanId(Integer oldmanId) {

        //查询老人
        Oldman oldman = new Oldman();
        oldman.setOldmanId(oldmanId);
        oldman = oldmanService.selectByOld(oldman);
        if(oldman == null){
            throw new OmcBizException(ErrorCodeEnum.OMC10038002);
        }
        if(!oldman.getStatus().equals(Constant.YIRUYUAN)){
            throw new OmcBizException(ErrorCodeEnum.OMC10031209);
        }

        //查询老人账户
        OmcOldManAccountFunds oldManAccountFunds = new OmcOldManAccountFunds();
        oldManAccountFunds.setOldManId(oldmanId.longValue());
        oldManAccountFunds = omcOldManAccountFundsService.selectOne(oldManAccountFunds);
        if(oldManAccountFunds == null){
            throw new OmcBizException(ErrorCodeEnum.OMC10037030);
        }

        //查询入院账单
        OmcOldManBill oldManBill = new OmcOldManBill();
        oldManBill.setIsPassed(1);
        oldManBill.setBillType(1);
        oldManBill.setOldManId(oldmanId.longValue());
        List<OmcOldManBill> omcOldManBills = omcOldmanBillService.select(oldManBill);

//        if(oldManBill == null){
//            throw new OmcBizException(ErrorCodeEnum.OMC10038014);
//        }

        /*
         * 2020-07-28
         * xcr
         * 二次入院-选择最新入院账单的信息
         * */
        if(omcOldManBills != null && omcOldManBills.size() > 0){
            oldManBill = omcOldManBills.get(0);
            for (OmcOldManBill bill : omcOldManBills) {
                if(bill.getCreatedTime().compareTo(oldManBill.getCreatedTime()) > 0){
                    oldManBill = bill;
                }
            }
        }else{
            throw new OmcBizException(ErrorCodeEnum.OMC10038014);
        }

        //创建返回对象
        AccountFundsOfLeyiVo vo = new AccountFundsOfLeyiVo();
        BeanUtils.copyProperties(oldManAccountFunds,vo);
        BigDecimal pledge = BigDecimal.ZERO;
        vo.setOldName(oldman.getOldName());

        //查询押金
        OmcBillItem billItemQuery = new OmcBillItem();
        billItemQuery.setBillId(oldManBill.getId());
        List<OmcBillItem> billItemList = omcBillItemService.select(billItemQuery);
        for(OmcBillItem item : billItemList){
            if (PublicUtil.isNotEmpty(item.getIsOutReturn())&&PublicUtil.isNotEmpty(item.getModelCode())){
                if(item.getIsOutReturn().equals(1) && item.getModelCode().equals(1)){
                    pledge = pledge.add(item.getActualFee());
                }
            }
        }
        vo.setBalance(oldManAccountFunds.getRemainder().add(pledge));
        vo.setPledge(pledge);
        return vo;
    }

    @Override
    public int ensureOldmanFee(Integer oldmanId, LoginAuthDto loginAuthDto) {

        //查询老人
        Oldman oldman = new Oldman();
        oldman.setOldmanId(oldmanId);
        oldman = oldmanService.selectByOld(oldman);
        if(oldman == null){
            throw new OmcBizException(ErrorCodeEnum.OMC10038002);
        }
        if(!oldman.getStatus().equals(Constant.YIRUYUAN)){
            throw new OmcBizException(ErrorCodeEnum.OMC10031209);
        }

        OldmanLeave oldmanLeave = new OldmanLeave();
        oldmanLeave.setOldmanId(oldmanId);
        oldmanLeave.setModifier(loginAuthDto.getUserId());

        /*
        * 2020-07-22
        * xcr
        * 二次入院
        * 老人出院时，在oldmanLeave对象中加入机构id，用于出院记录的查询
        * */
        oldmanLeave.setGroupId(oldman.getHomeId().longValue());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            oldmanLeave.setLeaveDate(sdf.parse(DateUtil.getCurrentDate()));
            oldmanLeave.setCreateTime(sdf.parse(DateUtil.getCurrentDate()));
            oldmanLeave.setModifyTime(sdf.parse(DateUtil.getCurrentDate()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int n = updateByOid(oldmanLeave);

        //出院该老人
        oldman.setStatus(OldInConstant.YICHUYUAN);
        //oldman.setHomeId(null);
        oldmanService.checkOut(oldman);

        Bed bed = new Bed();
        bed.setOldmanId(oldmanId);
        bed = bedService.selectByBed(bed);
        if(bed != null){
            int ret = bedService.cleanOldmanById(bed.getBedId());
            redisInitRunner.refreshBed(bed.getBedId());
        }

        // 刷新缓存
        redisInitRunner.refreshOldman(oldmanId);

        //出院后清空老人余额 保留消费金额和预缴金额
        OmcOldManAccountFunds oldManAccountFunds = new OmcOldManAccountFunds();
        oldManAccountFunds.setOldManId(oldmanId.longValue());
        oldManAccountFunds = omcOldManAccountFundsService.selectOne(oldManAccountFunds);
        if(oldManAccountFunds == null){
            throw new OmcBizException(ErrorCodeEnum.OMC10037030);
        }
        oldManAccountFunds.setRemainder(BigDecimal.ZERO);
        oldManAccountFunds.setRecharge(BigDecimal.ZERO);
        int retAccount = omcOldManAccountFundsService.update(oldManAccountFunds);

        //清除暂存的床位id,支付状态，入院日期
        OmcOldManSupplement oldManSupplement = new OmcOldManSupplement();
        oldManSupplement.setOldManId(oldmanId.longValue());
        oldManSupplement = omcOldManSupplementService.selectOne(oldManSupplement);
        oldManSupplement.setBedId(null);
        oldManSupplement.setIsPayed(0);
        oldManSupplement.setInDate(null);
        omcOldManSupplementService.updateById(oldManSupplement);

        /*
        * 2020-07-28
        * xcr
        * 二次入院-清空老人入院时选的项目
        * */
        OmcOldmanExpenseItem item = new OmcOldmanExpenseItem();
        item.setOldmanId(oldmanId.longValue());
        int j = omcOldmanExpenseItemService.delete(item);

        //根据老人Id删除评估及小项信息
        Integer k = cacRpcService.deleteByOldmanId(oldmanId);

        return n;
    }

    @Override
    public List<OldmanLeaveVo> queryOldmanLeaveListWithPage(ShowAllLeaveDto dto) {
        List<OldmanLeaveVo> oldmanLeaveVos = oldmanLeaveMapper.queryOldmanLeaveListWithPage(dto);
        /*for (OldmanLeaveVo oldmanLeaveVo : oldmanLeaveVos) {
            if (oldmanLeaveVo.getStatus()==3||oldmanLeaveVo.getStatus()==0||oldmanLeaveVo.getStatus()==1||oldmanLeaveVo.getStatus()==2){
                oldmanLeaveVo.setLeaveDate(null);
            }
        }*/
        return oldmanLeaveVos;
    }

    @Override
    public List<OldmanLeaveVo> listPage(ShowAllLeaveDto dto) {
        return oldmanLeaveMapper.listPage(dto);
    }
}
